const ID_PREFIX = 'graphic-'
const USE_OPENING_TAG = '<use xlink:href="#'

export function genSymboleId(id) {
  const symbolId = `${ID_PREFIX}${id}`;
  return symbolId;
}

export function composeSvg(viewBox, symbolDefs, useTags) {
  return `<svg href:xmlns="http://www.w3.org/2000/svg" viewBox="${viewBox}"> ${symbolDefs} ${useTags} </svg>`
}

export function composeUseTag({ x, y, width, height, graphicId }) {
  const symbolId = genSymboleId(graphicId)
  return `${USE_OPENING_TAG}${symbolId}" x="${x}" y="${y}" width="${width}" height="${height}" />`;
}

export function svgToSymbole({ svgCode, id }) {
  const symbolId = genSymboleId(id)
  const viewBox = matchViewBox(svgCode);
  const svgContent = svgCode.trim()
    .replace(/<svg(S*?)[^>]*>/, '')
    .replace(/<\/svg>$/, '');
  return `<symbol id="${symbolId}" viewBox="${viewBox}">${svgContent}</symbol>`;
}

export function colorUseTag(svgCode, id, color) {
  const symbolId = genSymboleId(id)
  const regStr = `${USE_OPENING_TAG}${symbolId}"([^>]*)\/>`
  const regExp = new RegExp(regStr, 'g');
  return svgCode.replace(regExp, (match, position) => {
    return `${USE_OPENING_TAG}${symbolId}"#graphic-1"${position} fill="${color}"/>`;
  });
}

/*
export function colorUseTag(svgCode, id, color) {
  const symbolId = genSymboleId(id)
  const regStr = `${USE_OPENING_TAG}${symbolId}"(.*?)\/>`
  const reg = new RegExp(regStr);
  const replaceStr = `${USE_OPENING_TAG}${symbolId}"$1 fill="${color}" />`
  return svgCode.replace(reg, replaceStr);
}
*/

export function matchViewBox(svgCode = '') {
  const viewBoxMatch = svgCode.match(/viewBox="([^"]+)"/);
  const match = svgCode.match(/viewBox="([^"]+)"/);
  return match ? match[1] : null;
}

